package com.service.Impl;

import com.entity.Coupon;
import com.exception.AddException;
import com.exception.UpdateException;
import com.github.pagehelper.PageInfo;
import com.mapper.CouponMapper;
import com.service.CouponService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @ClassName CouponServiceImpl
 * @Description 优惠券业务层实现类
 * @Author Kx
 * @Date 2025/5/28 19:28
 * @Version 1.0
 */
@Service("couponService")
public class CouponServiceImpl implements CouponService {
    private final CouponMapper couponMapper;

    public CouponServiceImpl(CouponMapper couponMapper) {
        this.couponMapper = couponMapper;
    }

    /**
     * @param coupon : 优惠券信息
     * @author: kx
     * @date: 2025/5/28 19:34
     * @description: 添加优惠券信息
     */
    @Transactional
    @Override
    public void addCoupon(Coupon coupon) {
        // 设置创建时间为当前时间
        coupon.setCreateAt(new Date());
        try {
            couponMapper.addCoupon(coupon);
        } catch (Exception e) {
            throw new AddException(1002, "添加优惠券失败");
        }
    }

    /**
     * @author: kx
     * @date: 2025/5/28 20:07
     * @param coupon : 优惠券信息
     * @description: 修改优惠券信息
    */
    @Transactional
    @Override
    public void updateCoupon(Coupon coupon) {
        try {
            // 查询优惠券信息
            Coupon ByCoupon = couponMapper.findById(coupon.getCouponId());
            // 把剩余的优惠券数量设置为原来的优惠券数量
            coupon.setRemainingQuantity(ByCoupon.getRemainingQuantity());
            if (ByCoupon.getRemainingQuantity() == 1) {
                coupon.setStatus(true);
            }
            couponMapper.updateCoupon(coupon);
        } catch (Exception e) {
            e.printStackTrace();
            throw new UpdateException(1003, "修改优惠券失败");
        }
    }

    /**
     * @author: kx
     * @date: 2025/6/19 11:58
     * @param pageNum : 页码
     * @param pageSize : 每页显示数量
     * @return com.github.pagehelper.PageInfo<com.entity.Coupon>
     * @description: 分页查询优惠券信息
    */
    @Override
    public PageInfo<Coupon> getPagedCoupons(Integer pageNum, Integer pageSize) {
        if (!couponMapper.getPagedCoupons(pageNum, pageSize).isEmpty()) {
            return PageInfo.of(couponMapper.getPagedCoupons(pageNum, pageSize));
        }
        throw new UpdateException(1001, "没有查询到优惠券信息");
    }
}
